#pragma once
#include <iostream>
#include <sys/epoll.h>
#include "Log.hpp"

class Epoller
{
    static const int epoll_size = 128;
public:

    Epoller():_epfd(-1)
    {}
    
    void Init()
    {
        _epfd = epoll_create(epoll_size);
    }

    void Add(int fd, uint32_t events)
    {
        struct epoll_event ev;
        ev.data.fd = fd;
        ev.events = events;
        int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, fd, &ev);
        if(n == -1)
        {
            LOG(Error, "epoll add fd: %d fail\n", fd);
            return;
        }
        LOG(Error, "epoll add fd: %d success\n", fd);
    }

    void Mod(int fd, uint32_t events)
    {
        struct epoll_event ev;
        ev.data.fd = fd;
        ev.events = events;
        int n = epoll_ctl(_epfd, EPOLL_CTL_MOD, fd, &ev);
        if(n == -1)
        {
            LOG(Error, "epoll mod fd: %d fail\n", fd);
            return;
        }
        LOG(Error, "epoll mod fd: %d success\n", fd);
    }

    void Del(int fd)
    {
        int n = epoll_ctl(_epfd, EPOLL_CTL_DEL, fd, nullptr);
        if(n == -1)
        {
            LOG(Error, "epoll del fd: %d fail\n", fd);
            return;
        }
        LOG(Error, "epoll del fd: %d success\n", fd);        
    }


    int Wait(struct epoll_event* events, int maxevents)
    {
        int timeout = -1;
        int n = epoll_wait(_epfd, events, maxevents, timeout);
        return n;
    }

    ~Epoller(){}

private:
    int _epfd;
};